package com.quickcode.example.threadpool;

import lombok.AllArgsConstructor;

import java.util.concurrent.*;

/**
 * 任务拆分线程及队列
 */
public class ForkJoinPoolExample1 {

    public static final ExecutorService WORK_POOL = Executors.newWorkStealingPool();

    public static void main(String[] args) {
        MyTask myTask = new MyTask(1, 100);
        ForkJoinTask<Integer> fork = myTask.fork();
        Integer value = fork.join();
        System.out.println("sum:" + value);


    }

    @AllArgsConstructor
    static class MyTask extends RecursiveTask<Integer> {

        private int start;

        private int end;

        @Override
        protected Integer compute() {
            if (end - start < 6) {
                return sum(start, end);
            } else {
                int mid = (end - start) / 2 + start;
                MyTask first = new MyTask(start, mid);
                MyTask last = new MyTask(mid + 1, end);
                first.fork();
                last.fork();
                return first.join() + last.join();
            }
        }

        public static int sum(int start, int end) {
            int sum = 0;
            for (int i = 0; i + start <= end; i++) {
                sum += start + i;
            }
            return sum;
        }
    }
}